package com.simple.base.core.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.simple.base.common.exception.BizException;
import com.simple.base.common.result.BaseResultCode;
import com.simple.base.core.repository.entity.SysUser;
import com.simple.base.core.repository.mapper.SysUserMapper;
import com.simple.base.core.service.ISysUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author kin
 * @since 2017-12-19
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Override
    public SysUser login(String account, String password) {
        SysUser sysUser = this.selectOne(new EntityWrapper<SysUser>()
                .eq("account", account)
                .eq("password", DigestUtils.md5Hex(password))
        );

        if (sysUser == null) {
            throw new BizException(BaseResultCode.ACCOUNT_PASSWORD_ERROR);
        }

        return sysUser;
    }

    @Override
    public Set<String> getPermission(Long userId) {
        List<String> permsList;


        permsList = baseMapper.queryAllPerms(userId);

        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for (String perms : permsList) {
            if (StringUtils.isBlank(perms)) {
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }
}
